import os
import time
import matplotlib.pyplot as plt
import csv

def convertTimestamp(time_str):
    # time_str = "03/18/23 10:54:00"
    timeConv = time_str.split(":")
    timeStamp = float(timeConv[0])*3600 + float(timeConv[1])*60 + float(timeConv[2])
    return timeStamp


def readFACTLog(fileName):
    with open(fileName, "r") as f:
        logs = f.readlines()
    return logs


def checkTestTime(logs):
    startTime = {}
    endTime = {}
    TTbreakdown = {}
    for e in logs:
        if e.find("Running") >=0:
            item = e.split()
            testName = item[5]
            if testName == "Test":
                testName = "Total"
            start = item[2]
            startTime[testName] = convertTimestamp(start)
        elif e.find("Finished") >=0:
            item = e.split()
            testName = item[5]
            if testName == "Test":
                testName = "Total"
            finish = item[2]
            endTime[testName] = convertTimestamp(finish)

    for e in startTime:
        testTime = endTime[e] - startTime[e]
        TTbreakdown[e] = testTime
    return TTbreakdown


def createCSV(TTbreakdown, fileName):
    titleRow = ["TestName", "Duration"]
    dataRow = []
    for key in TTbreakdown:
        dataRow.append({"TestName":key,"Duration":TTbreakdown[key]})
    with open(fileName, "a", newline = '') as f:
        writer = csv.DictWriter(f, fieldnames=titleRow)
        writer.writeheader()
        writer.writerows(dataRow)
    print("CSV output: ", fileName)
    return fileName


def drawPlot(TTbreakdown):
    testName = []
    testTime = []
    for key in TTbreakdown:
        testName.append(key)
        testTime.append(TTbreakdown[key])

    testName = testName[::-1]
    testTime = testTime[::-1]
    testName.pop()
    testTime.pop()

    barhPlot = plt.barh(testName, testTime, color = [(0.5,0,0), (0,0.5,0), (0,0,0.5)])
    plt.bar_label(barhPlot, label_type = 'edge')
    plt.title("TT Breakdown")
    plt.show()
    plt.close()

if __name__ == '__main__':
    fileName = "FACT-L-Cal.log"
    csvname = "FACT-L_Cal.csv"
    logs = readFACTLog(fileName)
    record = checkTestTime(logs)
    createCSV(record, csvname)
    drawPlot(record)

